using Microsoft.AspNetCore.Mvc;
using AdminSG3L.Applicaticn.ServicesInterface;
using AdminSG3L.Domain.Entities;
using AdminSG3L.Applicaticn.Commands;
using Serilog;
using AdminSG3L.Applicaticn.Dtos;
using Microsoft.AspNetCore.Authorization;

namespace AdminSG3L.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class RoleController(IRoleService roleService) : ControllerBase
{
    private readonly IRoleService _roleService = roleService;

    [HttpGet("{id}")]
    public async Task<ApiResponse<RoleDto?>> GetById(Guid id)
    {
        try
        {
            return await _roleService.GetDtoByIdAsync(id);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.GetById异常，Id={RoleId}", id);
            return ApiResponse<RoleDto?>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost]
    public async Task<ApiResponse<RoleDto>> Create([FromBody] CreateRoleDto dto)
    {
        try
        {
            return await _roleService.CreateAsync(dto);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.Create异常，Role={Role}", dto);
            return ApiResponse<RoleDto>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("batch")]
    public async Task<ApiResponse<IEnumerable<RoleDto>>> BatchCreate([FromBody] IEnumerable<CreateRoleDto> dtos)
    {
        try
        {
            return await _roleService.BatchCreateAsync(dtos);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.BatchCreate异常");
            return ApiResponse<IEnumerable<RoleDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPut]
    public async Task<ApiResponse<bool>> Update([FromBody] UpdateRoleDto dto)
    {
        try
        {
            return await _roleService.UpdateAsync(dto);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.Update异常，Role={Role}", dto);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpDelete("{id}")]
    public async Task<ApiResponse<bool>> Delete(Guid id)
    {
        try
        {
            return await _roleService.DeleteAsync(id);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.Delete异常，Id={RoleId}", id);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("batch-delete")]
    public async Task<ApiResponse<int>> BatchDelete([FromBody] IEnumerable<Guid> ids)
    {
        try
        {
            return await _roleService.BatchDeleteAsync(ids);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.BatchDelete异常");
            return ApiResponse<int>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpGet]
    public async Task<ApiResponse<IEnumerable<RoleDto>>> GetAll()
    {
        try
        {
            return await _roleService.GetAllDtoAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.GetAll异常");
            return ApiResponse<IEnumerable<RoleDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpGet("paged")]
    public async Task<ApiResponse<object>> GetPaged(
        int pageIndex, 
        int pageSize, 
        string? name = null, 
        string? code = null, 
        int? status = null)
    {
        try
        {
            // 创建筛选条件对象
            var filter = new RoleFilterDto
            {
                Name = name,
                Code = code,
                Status = status
            };
            
            var result = await _roleService.GetPagedFilteredDtoAsync(pageIndex, pageSize, filter);
            if (result.IsSuccess)
            {
                var (roles, totalCount) = result.Data;
                var pagedResult = new
                {
                    Roles = roles,
                    TotalCount = totalCount,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    TotalPages = (int)Math.Ceiling((double)totalCount / pageSize)
                };
                return ApiResponse<object>.Success(pagedResult);
            }
            return ApiResponse<object>.Fail(result.Message);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.GetPaged异常, 筛选条件: {name}, {code}, {status}", name, code, status);
            return ApiResponse<object>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpGet("count")]
    public async Task<ApiResponse<int>> GetCount()
    {
        try
        {
            return await _roleService.GetCountAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.GetCount异常");
            return ApiResponse<int>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("{roleId}/assign-permission/{permissionId}")]
    public async Task<ApiResponse<bool>> AssignPermission(Guid roleId, Guid permissionId)
    {
        try
        {
            return await _roleService.AssignPermissionAsync(roleId, permissionId);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.AssignPermission异常，RoleId={RoleId}, PermissionId={PermissionId}", roleId, permissionId);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("{roleId}/remove-permission/{permissionId}")]
    public async Task<ApiResponse<bool>> RemovePermission(Guid roleId, Guid permissionId)
    {
        try
        {
            return await _roleService.RemovePermissionAsync(roleId, permissionId);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.RemovePermission异常，RoleId={RoleId}, PermissionId={PermissionId}", roleId, permissionId);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }



    // 获取角色的所有权限
    [HttpGet("{roleId}/permissions")]
    public async Task<ApiResponse<IEnumerable<PermissionDto>>> GetRolePermissions(Guid roleId)
    {
        try
        {
            return await _roleService.GetRolePermissionsAsync(roleId);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.GetRolePermissions异常，RoleId={RoleId}", roleId);
            return ApiResponse<IEnumerable<PermissionDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("{roleId}/assign-menu/{menuId}")]
    public async Task<ApiResponse<bool>> AssignMenu(Guid roleId, Guid menuId)
    {
        try
        {
            return await _roleService.AssignMenuAsync(roleId, menuId);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.AssignMenu异常，RoleId={RoleId}, MenuId={MenuId}", roleId, menuId);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("{roleId}/remove-menu/{menuId}")]
    public async Task<ApiResponse<bool>> RemoveMenu(Guid roleId, Guid menuId)
    {
        try
        {
            return await _roleService.RemoveMenuAsync(roleId, menuId);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.RemoveMenu异常，RoleId={RoleId}, MenuId={MenuId}", roleId, menuId);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpGet("{roleId}/menus")]
    public async Task<ApiResponse<IEnumerable<object>>> GetRoleMenus(Guid roleId)
    {
        try
        {
            return await _roleService.GetRoleMenusAsync(roleId);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "RoleController.GetRoleMenus异常，RoleId={RoleId}", roleId);
            return ApiResponse<IEnumerable<object>>.Fail($"控制器异常: {ex.Message}");
        }
    }
} 